package xin.nick.manager;


import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import lombok.RequiredArgsConstructor;
import org.jose4j.jwt.JwtClaims;
import org.jose4j.jwt.consumer.InvalidJwtException;
import org.jose4j.lang.JoseException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import xin.nick.config.SystemProperties;
import xin.nick.constant.SystemConstants;
import xin.nick.entity.LoginUser;
import xin.nick.util.JwtUtil;

import java.util.concurrent.TimeUnit;

/**
 * @author Nick
 * @since 2022/12/5/005
 */
@Component
@RequiredArgsConstructor
public class LoginManager {

    private final RedisTemplate<String, Object> redisTemplate;
    private final SystemProperties systemProperties;

    /**
     * 设置登录用户token
     *
     * @param loginUser LoginUser
     */
    public void setLoginUserToken(LoginUser loginUser) {
        Long userId = loginUser.getUserId();
        String userIdString = String.valueOf(userId);
        AES aes = SecureUtil.aes(systemProperties.getAesSecret().getBytes());
        String subString = aes.encryptHex(userIdString);

        // token
        JwtClaims jwtClaims = JwtUtil.createJwtClaims(subString);
        jwtClaims.setIssuer(SystemConstants.APP_NAME);
        try {
            String token  = JwtUtil.createJwt(jwtClaims, systemProperties.getJwtSecret());
            loginUser.setToken(token);

            // 设置Redis登录信息, 根据用户id设置token缓存，在登录的时候，用于校验，同时可以确保用户只允许登录一个
            String tokenKey = SystemConstants.USER_TOKEN_KEY + userId;
            redisTemplate.opsForValue().set(tokenKey, token);
            redisTemplate.expire(tokenKey, SystemConstants.USER_TOKEN_EXPIRE, TimeUnit.SECONDS);

        } catch (JoseException e) {
            throw new RuntimeException(e);
        }


    }

    public static void main(String[] args) throws InvalidJwtException {
//        HashMap<String, Object> payloadMap = new HashMap<String, Object>();
//        payloadMap.put("token", SystemConstants.HEADER_AUTHORIZATION);
//        String token = JWTUtil.createToken(payloadMap, "CaseIamAFox".getBytes());
//        System.out.println(token);
//        String s = "1234567891234567";
//        System.out.println(s);
//        AES aes = SecureUtil.aes(s.getBytes());
//
//        String subString = aes.encryptHex("3234234");
//        System.out.println(subString);
//
//        String json = aes.decryptStr(subString);
//        System.out.println(json);


        String jwt = "..-Ihss";

        JwtClaims jwtClaims = JwtUtil.getJwtClaims(jwt, "");
        System.out.println(jwtClaims.getRawJson());


    }

}
